import { Injectable } from "@nestjs/common";

@Injectable()
export class JsonApiResponse {
    static new ($data,$message='成功',$status=0) : Object {

        let temp =  {'status' : $status,'message': $message,'data' : $data};
        
        let json = JSON.stringify(temp)

        const regex =new RegExp(/"([a-z]+[A-Z].*?)":/g);

        let index = 0

        let matchs = null;

        while(index < json.length && (matchs = regex.exec(json.substring(index + index?matchs[0].length : 0))))
        {
            let comps = matchs[1].match(/([A-Z][a-z]+)+?/g)
            let keys : [] = comps.map(o=>o.toLowerCase())
            let str : never = matchs[1].match(/[a-z]+/)[0] as never
            keys.unshift(str)
            // console.log(keys.join('_'));

            let repl = `"${keys.join('_')}":`
            json = json.replaceAll(matchs[0],repl)
            index += repl.length
        }

        // temp = JSON.parse(json)

        return json
    }

    static string($data,$message='成功',$status=0) : Object {
        let res =  {'status' : $status,'message': $message,'data' : $data};
        return res
    }

    static object($data,$message='成功',$status=0) : Object {
        let res =  {'status' : $status,'message': $message,'data' : $data};
        return res
    }

    static html($data,$message='成功',$status=0) : Object {
        return $data
    }

    static OK() : Object{
        return JsonApiResponse.new(null,'OK');
    }

    static ERR($message = '发生错误',$status = -1) : Object {
        return JsonApiResponse.string(undefined,$message,$status);
    }
}